package z_mxsTest.testArxmlSomeip.common;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import z_mxsTest.testArxmlSomeip.ArxmlPackageParser;

import java.util.List;

public abstract class BaseArxmlParser implements ArxmlPackageParser {

    // ✅ 新增的静态方法
    public static void printRootNode(String tagName, String shortName) {
        System.out.println("└── 模块类型: " + tagName + ", 名称: " + shortName);
    }

    @Override
    public void parse(Element packageElement) {
        parseChildren(packageElement, List.of(this));
    }

    protected void parseChildren(Element parent, List<ArxmlPackageParser> allParsers) {
        parseChildrenWithIndent(parent, allParsers, 1);
    }

    private void parseChildrenWithIndent(Element parent, List<ArxmlPackageParser> allParsers, int indentLevel) {
        NodeList children = parent.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element childElement = (Element) node;

                String tagName = childElement.getTagName();
                String shortName = XmlParseComm.getTextContent(childElement, "SHORT-NAME");

                // 打印当前节点信息
                printNodeWithIndent(tagName, shortName, indentLevel);

                // 尝试使用解析器处理
                boolean parsed = false;
                for (ArxmlPackageParser parser : allParsers) {
                    if (parser.supports(shortName)) {
                        parser.parse(childElement);
                        parsed = true;
                        break;
                    }
                }

                // 如果没有匹配的解析器，则继续递归解析
                if (!parsed) {
                    parseChildrenWithIndent(childElement, allParsers, indentLevel + 1);
                }
            }
        }
    }

    private void printNodeWithIndent(String tagName, String shortName, int indentLevel) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < indentLevel; i++) {
            sb.append("  ");
        }

        if (shortName != null && !shortName.isEmpty()) {
            sb.append("└─ ").append(tagName).append(": ").append(shortName);
        } else {
            sb.append("└─ ").append(tagName).append(": [无 SHORT-NAME]");
        }

        System.out.println(sb.toString());
    }
}



